# -*- coding: utf-8 -*-

from odoo import models, api, fields, _


class ZfyProcurementOrder(models.Model):
    _inherit = 'procurement.order'


    # remark = fields.Char(u'备注')

    # @api.multi
    # def _prepare_purchase_order(self, partner):
    #     res = super(ZfyProcurementOrder, self)._prepare_purchase_order(partner)
    #     res['sale_order_id'] = self.sale_line_id.order_id
    #     return res
    #
    # def _make_po_get_domain(self, partner):
    #     gpo = self.rule_id.group_propagation_option
    #     group = (gpo == 'fixed' and self.rule_id.group_id) or \
    #             (gpo == 'propagate' and self.group_id) or False
    #
    #     domain = (
    #         ('partner_id', '=', partner.id),
    #         ('state', '=', 'draft'),
    #         ('picking_type_id', '=', self.rule_id.picking_type_id.id),
    #         ('company_id', '=', self.company_id.id),
    #         ('dest_address_id', '=', self.partner_dest_id.id))
    #     if True:
    #         domain += (('sale_order_id', '=', self.sale_line_id.order_id.id),)
    #         print self.sale_line_id
    #         print self.partner_dest_id.id
    #     if group:
    #         domain += (('group_id', '=', group.id),)
    #     return domain

    @api.multi
    def make_po(self):
        cache = {}
        res = []
        for procurement in self:
            suppliers = procurement.product_id.seller_ids \
                .filtered(lambda r: (
                                    not r.company_id or r.company_id == procurement.company_id) and (
                                    not r.product_id or r.product_id == procurement.product_id))
            if not suppliers:
                procurement.message_post(body=_(
                    'No vendor associated to product %s. Please set one to fix this procurement.') % (
                                              procurement.product_id.name))
                continue
            supplier = procurement._make_po_select_supplier(suppliers)
            partner = supplier.name

            domain = procurement._make_po_get_domain(partner)

            if domain in cache:
                po = cache[domain]
            else:
                po = self.env['purchase.order'].search([dom for dom in domain],order='id desc')
                print po
                po = po[0] if po else False
                cache[domain] = po
            # fixed
            # vals = procurement._prepare_purchase_order(partner)
            # po = self.env['purchase.order'].create(vals)
            # name = (procurement.group_id and (
            #     procurement.group_id.name + ":") or "") + (
            #            procurement.name != "/" and procurement.name or procurement.move_dest_id.raw_material_production_id and procurement.move_dest_id.raw_material_production_id.name or "")
            # message = _(
            #     "This purchase order has been created from: <a href=# data-oe-model=procurement.order data-oe-id=%d>%s</a>") % (
            #               procurement.id, name)
            # po.message_post(body=message)
            # cache[domain] = po

            # origin
            if not po:
                vals = procurement._prepare_purchase_order(partner)
                po = self.env['purchase.order'].create(vals)
                name = (procurement.group_id and (
                procurement.group_id.name + ":") or "") + (
                       procurement.name != "/" and procurement.name or procurement.move_dest_id.raw_material_production_id and procurement.move_dest_id.raw_material_production_id.name or "")
                message = _(
                    "This purchase order has been created from: <a href=# data-oe-model=procurement.order data-oe-id=%d>%s</a>") % (
                          procurement.id, name)
                po.message_post(body=message)
                cache[domain] = po
            elif not po.origin or procurement.origin not in po.origin.split(', '):
                # Keep track of all procurements
                if po.origin:
                    if procurement.origin:
                        vals = procurement._prepare_purchase_order(partner)
                        po = self.env['purchase.order'].create(vals)
                        name = (procurement.group_id and (
                            procurement.group_id.name + ":") or "") + (
                                   procurement.name != "/" and procurement.name or procurement.move_dest_id.raw_material_production_id and procurement.move_dest_id.raw_material_production_id.name or "")
                        message = _(
                            "This purchase order has been created from: <a href=# data-oe-model=procurement.order data-oe-id=%d>%s</a>") % (
                                      procurement.id, name)
                        po.message_post(body=message)
                        po.write({'origin': procurement.origin})
                        # po.write(
                        #     {'origin': po.origin + ', ' + procurement.origin})
                    else:
                        po.write({'origin': po.origin})
                else:
                    if procurement.origin:
                        vals = procurement._prepare_purchase_order(partner)
                        po = self.env['purchase.order'].create(vals)
                        name = (procurement.group_id and (
                            procurement.group_id.name + ":") or "") + (
                                   procurement.name != "/" and procurement.name or procurement.move_dest_id.raw_material_production_id and procurement.move_dest_id.raw_material_production_id.name or "")
                        message = _(
                            "This purchase order has been created from: <a href=# data-oe-model=procurement.order data-oe-id=%d>%s</a>") % (
                                      procurement.id, name)
                        po.message_post(body=message)
                        po.write({'origin': procurement.origin})
                        # po.write(
                        #     {'origin': po.origin + ', ' + procurement.origin})
                    else:
                        po.write({'origin': po.origin})
                #     po.write({'origin': procurement.origin})
                # name = (self.group_id and (self.group_id.name + ":") or "") + (
                # self.name != "/" and self.name or self.move_dest_id.raw_material_production_id and self.move_dest_id.raw_material_production_id.name or "")
                # message = _(
                #     "This purchase order has been modified from: <a href=# data-oe-model=procurement.order data-oe-id=%d>%s</a>") % (
                #           procurement.id, name)
                # po.message_post(body=message)
            if po:
                res += [procurement.id]

            # Create Line
            po_line = False
            # for line in po.order_line:
            #     if line.product_id == procurement.product_id and line.product_uom == procurement.product_id.uom_po_id:
            #         procurement_uom_po_qty = procurement.product_uom._compute_quantity(
            #             procurement.product_qty,
            #             procurement.product_id.uom_po_id)
            #         seller = procurement.product_id._select_seller(
            #             partner_id=partner,
            #             quantity=line.product_qty + procurement_uom_po_qty,
            #             date=po.date_order and po.date_order[:10],
            #             uom_id=procurement.product_id.uom_po_id)
            #
            #         price_unit = self.env[
            #             'account.tax']._fix_tax_included_price_company(
            #             seller.price, line.product_id.supplier_taxes_id,
            #             line.taxes_id, self.company_id) if seller else 0.0
            #         if price_unit and seller and po.currency_id and seller.currency_id != po.currency_id:
            #             price_unit = seller.currency_id.compute(price_unit,
            #                                                     po.currency_id)
            #
            #         po_line = line.write({
            #             'product_qty': line.product_qty + procurement_uom_po_qty,
            #             'price_unit': price_unit,
            #             'procurement_ids': [(4, procurement.id)]
            #         })
            #         break
            if not po_line:
                vals = procurement._prepare_purchase_order_line(po, supplier)
                self.env['purchase.order.line'].create(vals)
        return res